package farmaciaweb.com.br.dao.impl;

import java.io.Serializable;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import farmaciaweb.com.br.dao.LaboratorioDAO;
import farmaciaweb.com.br.entity.Laboratorio;
import farmaciaweb.com.br.util.JPAUtil;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@PersistenceContext(unitName = "FarmaciaWebJPA")
public class LaboratorioDAOImpl implements LaboratorioDAO{

	private static final long serialVersionUID = 563803397889239394L;

	private EntityManager em;
	
	@Override
	public Laboratorio saveAtomic(Laboratorio laboratorio) {
		Laboratorio laboratorioSalva = null;
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			laboratorioSalva = this.em.merge(laboratorio);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			return null;
		}	
		
		return laboratorioSalva;	
	}
	
	@Override
	public void deleteAtomic(Laboratorio lab) {
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			this.em.remove(lab);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			e.getStackTrace();
		}	
		
	}

	
	public List<Laboratorio> pesquisarLaboratorio(String nome, String cnpj){
		Map<String, Object> listaParams;
		listaParams = new HashMap<String, Object>();
		listaParams.put("nome", nome);
		listaParams.put("cnpj", cnpj);		
		return JPAUtil.findByNamedQueryAndNamedParams("bd_farmaciaweb.consultaLaboratorio", listaParams);
	}
	
	public Laboratorio findById(int id){
		Laboratorio t = new Laboratorio();
		t = em.find(Laboratorio.class, id);
		return t;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Laboratorio> findAll() {
		this.em = JPAUtil.getEntityManger();
		Query query = this.em.createQuery("SELECT e FROM Laboratorio e ORDER BY e.nome");
		return query.getResultList();
	}
	
	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	
}
